<?php
require_once ('utils' . DIRECTORY_SEPARATOR . 'DeCaptcha.php');
require_once ('utils' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'simple_html_dom.php');
require_once ('utils' . DIRECTORY_SEPARATOR . 'HHAbstract.php');

set_time_limit(-1);

class HHSPlaceBids extends HHAbstract {

	const URL = 'http://www.hudhomestore.com/';
	public $capturedHtmlStep;

	function __construct() {
		parent::__construct();
	}

	function __destruct() {
		parent::__destruct();
	}

	function constructClass() {
		$this -> capturedHtmlStep = 1;

		//if($this->agentLogintoHomeStores('msmalabet','morRealty1!')){
		//			die('we are logged in');
		//}else{
		//			die('could not log in');
		//};
		
		$this -> handleARGV();
	}

	function handleARGV() {
		global $argv;
		if (!isset($argv) || count($argv) <= 1) {
			$this -> getUpdatedBidInfo();
			$this -> getNewBids();
		}
		else {
			array_shift($argv);
			foreach ($argv as $value) {
				$keyArray = split("=", $value);
				$key = $keyArray[0];
				$keyValue = $keyArray[1];
				switch ($key) {
					case "bidId" :
						$bidId = $keyValue;
						if (isset($bidId)) {
							$this -> placeBid($bidId);
						}
						break;
					case "checkAgentsBidStatus" :
						$agentId = $keyValue;
						echo('Agent ID to update bids: ' . $agentId . '<br>');
						if (isset($agentId)) {
							$this -> updateBids($agentId);
						}
						else {
							echo('Could not parse value from updateBids<br>');
						}
						break;
					default :
						echo("Incorrect argument usage. Please use one of the following:\n");
				}
			}
		}
	}

	private function getNewBids() {
		echo("<hr>Getting New Bids- " . date('Y-m-d h:i:s') . '<br>');

		// Get the new bids that havent been scheduled and the time has passed that have no bid_results, have no confirmation number,
		// user has confirmed, the user is still allowed by the agent, and group by the case ordered by the latest scheduled_submission time
		$query = 'SELECT 
			SUBSTRING_INDEX( GROUP_CONCAT(ub.id Order BY ub.scheduled_submission_time ASC) ,\',\',1) AS bidId 
			FROM user_bids AS ub 
			LEFT JOIN bid_results AS brs ON brs.`case` = ub.`case`
			INNER JOIN agent_license_allowed_users AS ala ON ala.agent_license_id = ub.license_id AND ala.user_id = ub.user_id
			WHERE 
			ub.user_confirmed=true 
			AND brs.case IS NULL  
			AND ub.confirmation_number IS NULL  
			AND DAYOFYEAR(ub.scheduled_submission_time) <=  DAYOFYEAR("' . date('Y-m-d') . '")
			group by ub.user_id, ub.`case` 
			order by RAND()';
		//$query .= 'limit 2';
		//echo('Place New Bids Query: ' . $query . '<br>');
		$result = $this -> runQuery($query, $this -> getDBConnection() -> getDBConnection());
		$className = get_class($this);
		$file = $className . ".txt";
		while (($row = $result -> fetch_assoc())) {
			$bidId = $row["bidId"];
			$cmd = $className . ".php bidId=" . $bidId;
			$this -> getCommandLineHelper() -> run_in_background($cmd, $file);
			//$this->placeBid($bidId); // TODO: remove when query is right
		}

	}

	function getUpdatedBidInfo() {
		echo('Getting Update bid info<br>');

		// Update bids that have been submitted with their statuses
		// Bids that have been submitted that have no status or the status is not canceled (maybe more criteria)
		$query = 'SELECT agent_id 
				FROM user_bids AS ub 
				WHERE  
				ub.confirmation_number IS NOT NULL 
				AND (bid_status IS NULL OR bid_status != "Cancelled" OR bid_status="Sealed Bid") 
				GROUP BY ub.agent_id
				';
		//echo('Update Bids Query: '.$query.'<br>');
		$result = $this -> runQuery($query, $this -> getDBConnection() -> getDBConnection());
		$className = get_class($this);
		$file = $className . ".txt";
		while (($row = $result -> fetch_assoc())) {
			$agentId = $row["agent_id"];
			$cmd = $className . ".php checkAgentsBidStatus=" . $agentId;
			echo('Update Bids Command: ' . $cmd . '<br>');
			$this -> getCommandLineHelper() -> run_in_background($cmd, $file);
			//$this->updateBids($agentId); // TODO: remove when query is right
		}
	}

	function updateBids($agentId, $bidIds = array()) {

		$limitToTheseBids = '';
		if (count($bidIds) > 0) {
			$limitToTheseBids = ' AND ub.id IN (' . implode(',', $bidIds) . ') ';
		}

		echo('<hr>Updating Bids for Agent ID: ' . $agentId . ' - ' . date('Y-m-d h:i:s') . '<br>');

		$query = 'SELECT ag.user, ag.pass, GROUP_CONCAT(CONCAT(ub.id,":",ub.confirmation_number)) AS bidIds
				FROM user_bids AS ub 
				LEFT JOIN agents AS ag on ag.id = ub.agent_id 
				WHERE  
				ub.confirmation_number IS NOT NULL 
				AND (bid_status IS NULL OR bid_status != "Cancelled" OR bid_status="Sealed Bid") 
				AND ub.agent_id=' . $agentId . '
				' . $limitToTheseBids . ' 
				GROUP BY ub.agent_id
				';

		$result = $this -> runQuery($query, $this -> getDBConnection() -> getDBConnection());
		$row = $result -> fetch_assoc();
		$bidIds = explode(',', $row["bidIds"]);
		$user = $row['user'];
		$pass = $row['pass'];

		$this -> setCookieFile('cookie_agent_id_' . $agentId . '.txt');

		// Login For the given agent
		if (!($this -> agentLogintoHomeStores($user, $pass))) {
			echo("Could not login for agent_id: " . $agentId . '<br>');
			return false;
		}

		echo('Agent Is Logged In<br>');

		//die('We are here');

		// Go through each given bid Id and update the database with its status
		foreach ($bidIds as $bidIdConfCombo) {
			$bidIdConfComboArray = explode(':', $bidIdConfCombo);
			$bidId = $bidIdConfComboArray[0];
			$confirmationNumber = $bidIdConfComboArray[1];

			//die("Bid ID $bidId : Confirmation: $confirmationNumber");

			$bidDetailsURL = 'https://www.hudhomestore.com/pages/BidDetails.aspx?Page=BidDetails&PageGroup=Bidder&SCONFIRMATIONNUMBER=' . $confirmationNumber . '&sLanguage=ENGLISH&iHeight=0';
			$bidDetailsHtml = $this -> get_web_page($bidDetailsURL);

			$html = str_get_html($bidDetailsHtml . ' ');

			//echo('HTML after Bid Details <br>'.$html.'<br><br><hr><br><br>');

			if ($html === false) {
				echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($bidDetailsURL) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
				return false;
			}
			else
			if ($this -> checkSessionExpired($html)) {
				echo("<b><font color='red'>Your Session has expired (After Bid Update Step " . $this -> capturedHtmlStep . "). Could not place bid</font></b><br>");
				$this -> logCapturedHtml($html, $bidId, 'update');
				return false;
			}
			$this -> logCapturedHtml($html, $bidId, 'update');

			$bidStatus = $html -> find('span[id=lblBidStatus]', 0) -> plaintext;

			if ($this -> updateBidWithBidStatus($bidId, $bidStatus)) {
				echo('Bid Id: ' . $bidId . ' updated with status=' . $bidStatus . '<br>');
			}
			else {
				echo('Bid Id: ' . $bidId . ' | Could not update status.<br>');
			}

			$counterOfferAmount = $html -> find('span[id=lblCounterOfferAmount]', 0) -> plaintext;

			if ($this -> updateBidWithBidCounterOfferAmount($bidId, $counterOfferAmount)) {
				echo('Bid Id: ' . $bidId . ' updated with counter offer amount=' . $counterOfferAmount . '<br>');
			}
			else {
				echo('Bid Id: ' . $bidId . ' | Could not find a counter offer or amount.<br>');
			}

		}

	}

	private function placeBid($bidId) {
		echo('<hr>Placing Bid for BidID: ' . $bidId . '<br>');
		$query = "SELECT 
			ub.id as bidId,
			ub.agent_id,  
			ag.user,
			ag.pass,
			agl.license,
			br.NAID,
			us.first_name AS `purchaser_first_name`,
			us.middle_name AS `purchaser_middle_name`,
			us.last_name AS `purchaser_last_name`,
			adr.address,
			adr.city,
			adr.state,
			adr.zip,
			ub.bid_amount,
			ub.finance_type,
			ub.seller_closing_cost,
			ub.broker_commission_cost,
			ub.purchaser_type,
			ub.accept_as_backup_offer,
			upi.value as `purchaser_id_number`,
			ub.`case`
			
			from user_bids AS ub 
			LEFT JOIN users as us ON us.id=ub.user_id 
			LEFT JOIN user_address as adr ON ub.user_address_id = adr.id AND adr.user_id=us.id 
			LEFT JOIN user_purchase_ids as upi ON upi.id= ub.user_purchase_id 
			LEFT JOIN agents as ag ON ag.id=ub.agent_id 
			LEFT JOIN agent_license as agl ON agl.agent_id=ag.id AND agl.id=ub.license_id 
			LEFT JOIN brokers as br ON br.id = ag.broker_id AND br.id = ub.broker_id 
			
			WHERE 
			ub.id=" . $bidId;
		//echo('Place full bid Query:<br> '.$query.'<br><br>');

		$result = $this -> runQuery($query, $this -> getDBConnection() -> getDBConnection());
		$bidInfo = $result -> fetch_assoc();

		$bidId = $bidInfo['bidId'];
		$caseNumber = $bidInfo['case'];
		session_name($caseNumber . '_' . $bidId);
		session_start();
		$this -> placeBidOnCase($bidInfo);
		session_destroy();
	}

	public function placeBidOnCaseAsCounterOffer(array $bidInfo) {
		$bidId = $bidInfo['bidId'];
		$caseNumber = $bidInfo['case'];
		$agentId = $bidInfo['agent_id'];

		echo('The following bid needs to be places as counter offer. Bid ID: ' . $bidId . '<br>');
		//var_dump($bidInfo);
		//echo('<br>');

		$query = 'SELECT user, pass 
		FROM agents AS ag 
		WHERE 
		ag.id = ' . $agentId;

		$result = $this -> runQuery($query, $this -> getDBConnection() -> getDBConnection());
		$row = $result -> fetch_assoc();
		$user = $row['user'];
		$pass = $row['pass'];

		// Login For the given agent
		if (!$this -> agentLogintoHomeStores($user, $pass)) {
			echo("Could not login for agent_id: " . $agentId . '<br>');
			return false;
		}

		echo('Agent Is Logged In<br>');

		//Use the prvious bids confirmation number and go to the bid details page
		$confirmationNumber = $this -> getPreviousBidConfirmationNumber($bidId);

		if ($confirmationNumber === false) {
			echo('Could Not Find the Previous Confirmation Number ');
		}

		$bidDetailsUrl = 'https://www.hudhomestore.com/pages/BidDetails.aspx?Page=BidDetails&PageGroup=Bidder&SCONFIRMATIONNUMBER=' . $confirmationNumber . '&sLanguage=ENGLISH&iHeight=0';
		$bidDetailsHTML = $this -> get_web_page($bidDetailsUrl);

		$html = str_get_html($bidDetailsHTML . ' ');

		//echo('HTML after home page <br>'.$html.'<br><br><hr><br><br>');

		if ($html === false) {
			echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($bidDetailsUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
			return false;
		}
		else
		if ($this -> checkSessionExpired($html)) {
			echo("<b><font color='red'>Your Session has expired (After Counter Offer Step " . $this -> capturedHtmlStep . "). Could not place bid</font></b><br>");
			$this -> logCapturedHtml($html, $bidId, 'counter_offer');
			return false;
		}
		$this -> logCapturedHtml($html, $bidId, 'counter_offer');

		// Post to the bid details page that we want to counter
		$postData = array(
			'btnCounterOfferBid' => 'Counter Offer Bid',
			'txtAMNotes' => null,
			'txtFSMNotes' => null,
		);

		foreach ($html->find('input[type=hidden]') as $hiddenInput) {
			if (!isset($postData[$hiddenInput -> name])) {
				$postData[$hiddenInput -> name] = $hiddenInput -> value;
			}
		}

		//echo('Post Data:<br>');
		//var_dump($postData);
		//echo('<br>');

		$postDataAsString = http_build_query($postData);

		$additionalCurlOptions = array(
			CURLOPT_POST => 1,
			CURLOPT_POSTFIELDS => $postDataAsString,
		);

		$bidDetailsHTML = $this -> get_web_page($bidDetailsUrl, false, $additionalCurlOptions);

		$html = str_get_html($bidDetailsHTML . ' ');

		//echo('HTML after Loging in <br>'.$html.'<br><br><hr><br><br>');

		if ($html === false) {
			echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($bidDetailsUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
			return false;
		}
		else
		if ($this -> checkSessionExpired($html)) {
			echo("<b><font color='red'>Your Session has expired (After Counter Offer Step " . $this -> capturedHtmlStep . "). Could not place bid</font></b><br>");
			$this -> logCapturedHtml($html, $bidId, 'agent_login');
			return false;
		}
		$this -> logCapturedHtml($html, $bidId, 'counter_offer');

		// Then redirect to Bid Submission  Page
		//$bidUrl = 'https://www.hudhomestore.com/Listing/BidSubmission.aspx?sLanguage=ENGLISH';
		$bidUrl = 'https://www.hudhomestore.com/pages/BidSubmission.aspx?Page=BidSubmission&PageGroup=Listing&sLanguage=ENGLISH&iHeight=0';
		$bidHtml = $this -> get_web_page($bidUrl, false, array(CURLOPT_POST => false, ));

		$html = str_get_html($bidHtml . ' ');

		if ($html === false) {
			echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($bidUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
			return false;
		}
		else
		if ($this -> checkSessionExpired($html)) {
			echo("<b><font color='red'>Your Session has expired (After Counter Offer Step " . $this -> capturedHtmlStep . "). Could not place bid</font></b><br>");
			$this -> logCapturedHtml($html, $bidId, 'counter_offer');
			return false;
		}
		$this -> logCapturedHtml($html, $bidId, 'counter_offer');

		//TODO:  Need to determine if the counter offer is less than what we were going to offer. If so change $bidinfo to match so that the submission uses the counter offer amounts
		
		
		// Submit the Bid
		$submitSuccessfull = $this -> submitBidStep($html, $bidInfo);
		if ($submitSuccessfull) {
			echo('Counter Offer Bid Successfully Placed on Case: ' . $caseNumber . '<br>');
		}

	}

	function checkSessionExpired($html) {
		return (stripos($html, 'Your session has expired') !== false || stripos($html, 'Your session has timed out') !== false);
	}

	function logCapturedHtml($html, $bidId = null, $stepPrefix = 'submit') {
		$bidPrefix = '';
		if (isset($bidId)) {
			$bidPrefix = 'bid_' . $bidId . '_';
		}
		$file = realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . $bidPrefix . $stepPrefix . '_step_' . $this -> capturedHtmlStep . '.html';
		$html -> save($file);
		$this -> capturedHtmlStep++;
	}

	function previousBidStatusHasBeenUpdated($bidId) {
		$previouseStatusUpdated = true;
		$query = 'SELECT 
			IF(SUBSTRING_INDEX( GROUP_CONCAT(COALESCE(ub2.bid_status,\'no_status\') Order BY ub2.scheduled_submission_time DESC),\',\',1)=\'no_status\',false,true) AS hasStatusUpdated 
			FROM user_bids AS ub 
			LEFT JOIN user_bids AS ub2 ON ub2.`case` = ub.`case` 
			AND ub.user_id = ub2.user_id AND ub.agent_id = ub2.agent_id 
			AND ub.id!=ub2.id AND ub2.scheduled_submission_time<ub.scheduled_submission_time 
			WHERE 
			ub.id=' . $bidId . ' 
			AND ub2.confirmation_number IS NOT NULL 
			group by ub2.`case`
		';
		$result = $this -> runQuery($query, $this -> getDBConnection() -> getDBConnection());
		$row = $result -> fetch_assoc();
		if (isset($row['hasStatusUpdated']) && strlen($row['hasStatusUpdated']) > 0) {
			$previouseStatusUpdated = (bool)$row['hasStatusUpdated'];
		}
		return $previouseStatusUpdated;
	}

	function previousBidBeenOpened($bidId) {
		$previouseBidOpened = true;
		$query = 'SELECT 
			IF(SUBSTRING_INDEX( GROUP_CONCAT(COALESCE(ub2.bid_status,\'no_status\') Order BY ub2.scheduled_submission_time DESC),\',\',1)=\'Sealed Bid\',false,true) AS hasBeenOpened 
			FROM user_bids AS ub 
			LEFT JOIN user_bids AS ub2 ON ub2.`case` = ub.`case` 
			AND ub.user_id = ub2.user_id AND ub.agent_id = ub2.agent_id 
			AND ub.id!=ub2.id AND ub2.scheduled_submission_time<ub.scheduled_submission_time 
			WHERE 
			ub.id=' . $bidId . ' 
			AND ub2.confirmation_number IS NOT NULL 
			group by ub2.`case`
		';
		$result = $this -> runQuery($query, $this -> getDBConnection() -> getDBConnection());
		$row = $result -> fetch_assoc();
		if (isset($row['hasBeenOpened']) && strlen($row['hasBeenOpened']) > 0) {
			$previouseBidOpened = (bool)$row['hasBeenOpened'];
		}
		return $previouseBidOpened;
	}

	function previousBidHasCounterOffer($bidID) {
		// Look at the previous bid for the given bid and see if it has a counter offer
		$previousHasCounterOffer = false;
		$query = 'SELECT 
				SUBSTRING_INDEX( GROUP_CONCAT(ub2.has_counter_offer Order BY ub2.scheduled_submission_time DESC),\',\',1) AS hasBeenCountered 
				FROM user_bids AS ub 
				LEFT JOIN user_bids AS ub2 ON ub2.`case` = ub.`case` 
				AND ub.user_id = ub2.user_id AND ub.agent_id = ub2.agent_id 
				AND ub.id!=ub2.id AND ub2.scheduled_submission_time<ub.scheduled_submission_time 
				WHERE 
				ub.id=' . $bidID . ' 
				AND ub2.confirmation_number IS NOT NULL 
				group by ub2.`case`
		';
		$result = $this -> runQuery($query, $this -> getDBConnection() -> getDBConnection());
		$row = $result -> fetch_assoc();
		if (isset($row['hasBeenCountered']) && strlen($row['hasBeenCountered']) > 0) {
			$previousHasCounterOffer = (bool)$row['hasBeenCountered'];
		}
		return $previousHasCounterOffer;
	}

	function getPreviousBidConfirmationNumber($bidID) {
		// Look at the previous bid for the given bid and see if it has a counter offer
		$previousConfirmationNumber = false;
		$query = 'SELECT 
				SUBSTRING_INDEX( GROUP_CONCAT(ub2.confirmation_number Order BY ub2.scheduled_submission_time DESC),\',\',1) AS confirmation_number 
				FROM user_bids AS ub 
				LEFT JOIN user_bids AS ub2 ON ub2.`case` = ub.`case` 
				AND ub.user_id = ub2.user_id AND ub.agent_id = ub2.agent_id 
				AND ub.id!=ub2.id AND ub2.scheduled_submission_time<ub.scheduled_submission_time 
				WHERE 
				ub.id=' . $bidID . ' 
				AND ub2.confirmation_number IS NOT NULL 
				group by ub2.`case`
		';
		$result = $this -> runQuery($query, $this -> getDBConnection() -> getDBConnection());
		$row = $result -> fetch_assoc();
		if (isset($row['confirmation_number']) && strlen($row['confirmation_number']) > 0) {
			$previousConfirmationNumber = (bool)$row['confirmation_number'];
		}
		return $previousConfirmationNumber;
	}

	public function placeBidOnCase(array $bidInfo) {
		echo('Placing Bid on Case: ' . $bidInfo['case'] . '<br>');

		$validBidInfo = $this -> validBidInfo($bidInfo);
		if ($validBidInfo === true) {
			// Get all the information about the bid to place new bid
			$bidId = $bidInfo['bidId'];
			$caseNumber = $bidInfo['case'];
			$NAID = $bidInfo['NAID'];
			$RELicense = $bidInfo['license'];
			$this -> setCookieFile('cookie_bid_' . $bidId . '_case_' . $caseNumber . '.txt');

			// Check to make sure the previous bid status has been updated
			if (!$this -> previousBidStatusHasBeenUpdated($bidId)) {
				echo('The previous bid for id: ' . $bidId . ' has not been updated yet.');
				$this -> updateBids($bidInfo['agent_id'], array($bidId));
			}

			// Check to see if the previous status has been opened by HUD agent
			if (!$this -> previousBidBeenOpened($bidId)) {
				echo("We cannot place this bid id: $bidId because the previous bid as not been opened yet by HUD.");
				return false;
			}

			// Check to see if the previous bid has a counter offer so we can take that route
			if ($this -> previousBidHasCounterOffer($bidId)) {
				if ($this -> placeBidOnCaseAsCounterOffer($bidInfo)) {
					return true;
				}
				else {
					echo('Could not place bid id: ' . $bidId . ' as counter offer. Placing as new bid<br>');
				}
			}

			echo('Placing Bid on Case: ' . $caseNumber . '<br>');

			$startUrl = self::URL . "Listing/PropertyDetails.aspx?caseNumber=" . $caseNumber;
			//echo($this->getUrlAsLink($startUrl).'<br>');
			$hudhomestore = $this -> get_web_page($startUrl);

			$html = str_get_html($hudhomestore . ' ');

			//echo('HTML after Property Details <br>'.$html.'<br><br><hr><br><br>');

			if ($html === false) {
				echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($startUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
				return false;
			}
			else
			if ($this -> checkSessionExpired($html)) {
				echo("<b><font color='red'>Your Session has expired (After Submit Step " . $this -> capturedHtmlStep . "). Could not place bid</font></b><br>");
				$this -> logCapturedHtml($html, $bidInfo['bidId']);
				return false;
			}
			$this -> logCapturedHtml($html, $bidInfo['bidId']);

			$pattern = '/https:\/\/www\.hudhomestore\.com\/Listing\/NaidVerification\.aspx\?sLanguage=ENGLISH&caseNumber=(.*?)&/';
			$matches = array();
			preg_match($pattern, $html, $matches);
			$submitUrl = '';

			if (count($matches) > 0 && isset($matches[1])) {
				$encryptedCaseNumber = $matches[1];
				$submitUrl = 'https://www.hudhomestore.com/pages/NaidVerification.aspx?Page=NaidVerification&PageGroup=Listing&sLanguage=ENGLISH&caseNumber=' . $encryptedCaseNumber;

				//echo('Naid Verification Url: '.$this->getUrlAsLink($submitUrl).'<br>');
				$hudhomestoreSubmit = $this -> get_web_page($submitUrl);

				$html = str_get_html($hudhomestoreSubmit . ' ');

				if ($html === false) {
					echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($submitUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
					return false;
				}
				else
				if ($this -> checkSessionExpired($html)) {
					echo("<b><font color='red'>Your Session has expired (After Submit Step " . $this -> capturedHtmlStep . "). Could not place bid</font></b><br>");
					$this -> logCapturedHtml($html, $bidInfo['bidId']);
					return false;
				}
				$this -> logCapturedHtml($html, $bidInfo['bidId']);

				//echo('HTML after NAID Verification<br>'.$html.'<br><br><hr><br><br>');

				$hiddenInputData = array();
				foreach ($html->find('input[type=hidden]') as $hiddenInput) {
					if ($hiddenInput -> name != 'recaptcha_response_field') {
						$hiddenInputData[$hiddenInput -> name] = $hiddenInput -> value;

					}
				}

				//echo('Hidden Input Fields<br>');
				//var_dump($hiddenInputData);
				//echo('<br><br>');

				//die('<pre>'.$html.'</pre>');

				$js = null;
				$jsFound = array();
				foreach ($html->find('script') as $script) {
					$src = $script -> src;
					$jsFound[] = $src;
					if (stripos($src, 'www.google.com/recaptcha/api/challenge') !== false) {
						$js = $src;
						break;
					}
				}

				if (!isset($js)) {
					echo("<b><font color='red'>Could not find JS needed to get captcha information.</font></b>");
					echo("JS Found:<br>");
					var_dump($jsFound);
					echo("<br>");

					return false;
				}

				$googleRecaptchaAPiChallenge = $this -> get_web_page($js);
				$html = str_get_html($googleRecaptchaAPiChallenge . ' ');

				if ($html === false) {
					echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($js) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
					return false;
				}
				else
				if ($this -> checkSessionExpired($html)) {
					echo("<b><font color='red'>Your Session has expired (After Submit Step " . $this -> capturedHtmlStep . "). Could not place bid</font></b><br>");
					$this -> logCapturedHtml($html, $bidInfo['bidId']);
					return false;
				}
				$this -> logCapturedHtml($html, $bidInfo['bidId']);

				$pattern = '/challenge : \'(.*?)\'/';
				$matches = array();
				preg_match($pattern, $html, $matches);

				if (count($matches) > 0 && isset($matches[1])) {
					$captchaChallengeField = $matches[1];
					//$captchaChallengeField ='03AHJ_Vuuv09w0vYtZTIjEW_gP3dSqhy8B7pjT2z24w6PmP_vWCzr1a0LERB1_ncj-yB2JUi8XVHTcOW_KTynHWT6Wd1zGAaM_JHC6y9N1L37ivGQ0C5rbPTNLMKbwGaCxd3ds4uo09EGJ7y4FJWrpn9qp9QAgEj3U0Tz3L44lkkwRWRlp21LqH6rEzMOCjHj_JQ9KZdsgAYooqIvPaHozbjvZI8NAZ5I2mg';
					$captchaSrc = 'https://www.google.com/recaptcha/api/image?c=' . $captchaChallengeField;
				}

				//echo('Captcha Src:'.$this->getUrlAsLink($captchaSrc).'<br>');
				//echo('Captcha Feild:'.$captchaChallengeField.'<br>');

				$deCaptcha = new DeCaptcha(decaptchauser, decaptchapass);
				$captchaText = $deCaptcha -> getCatchaText($captchaSrc);
				//$captchaText = 'sylvius dshedeo';

				//echo("Solved Captcha: ".$captchaText.'<br>');

				$postData = array(
					'btnSubmit' => 'Verify NAID',
					'ddNaidType' => 'SellingBroker',
					'recaptcha_challenge_field' => $captchaChallengeField,
					'recaptcha_response_field' => $captchaText,
					'txtNAID' => $NAID,
					'txtRealEstateLicense' => $RELicense,
				);

				// Include the hidden input data
				foreach ($hiddenInputData as $index => $value) {
					$postData[$index] = $value;
				}

				$postDataAsString = http_build_query($postData);

				$additionalCurlOptions = array(
					CURLOPT_POST => 1,
					CURLOPT_POSTFIELDS => $postDataAsString,
				);

				$naidVerificationUrl = 'https://www.hudhomestore.com/pages/NaidVerification.aspx?Page=NaidVerification&PageGroup=Listing&sLanguage=ENGLISH&caseNumber=' . urldecode($encryptedCaseNumber) . "&Page=NaidVerification&PageGroup=Listing&iHeight=770";
				//$naidVerificationUrl = 'https://www.hudhomestore.com/pages/NaidVerification.aspx?Page=NaidVerification&PageGroup=Listing&sLanguage=ENGLISH&caseNumber=MjQxLTcxODg2MA%3d%3d&&iHeight=770';

				//echo("Naid Verification Url: ".$this->getUrlAsLink($naidVerificationUrl).'<br>');

				$hudhomestoreNaidVerification = $this -> get_web_page($naidVerificationUrl, false, $additionalCurlOptions);
				$html = str_get_html($hudhomestoreNaidVerification . ' ');

				if ($html === false) {
					echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($naidVerificationUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
					return false;
				}
				else
				if ($this -> checkSessionExpired($html)) {
					echo("<b><font color='red'>Your Session has expired (After Submit Step " . $this -> capturedHtmlStep . "). Could not place bid</font></b><br>");
					$this -> logCapturedHtml($html, $bidInfo['bidId']);
					return false;
				}
				$this -> logCapturedHtml($html, $bidInfo['bidId']);

				// Then redirect to Bid Page
				//$bidUrl = 'https://www.hudhomestore.com/Listing/BidSubmission.aspx?sLanguage=ENGLISH';
				$bidUrl = 'https://www.hudhomestore.com/pages/BidSubmission.aspx?Page=BidSubmission&PageGroup=Listing&sLanguage=ENGLISH&iHeight=0';
				$bidHtml = $this -> get_web_page($bidUrl, false, array(CURLOPT_POST => false, ));

				$html = str_get_html($bidHtml . ' ');

				if ($html === false) {
					echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($bidUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
					return false;
				}
				else
				if ($this -> checkSessionExpired($html)) {
					echo("<b><font color='red'>Your Session has expired (After Submit Step " . $this -> capturedHtmlStep . "). Could not place bid</font></b><br>");
					$this -> logCapturedHtml($html, $bidInfo['bidId']);
					return false;
				}
				$this -> logCapturedHtml($html, $bidInfo['bidId']);

				// Submit the Bid
				$submitSuccessfull = $this -> submitBidStep($html, $bidInfo);
				if ($submitSuccessfull) {
					echo('Bid Successfully Placed on Case: ' . $caseNumber . '<br>');
				}

			}
			else {
				die('Could not find the sumbit url for case: ' . $caseNumber);
			}

		}
		else {
			echo(implode("\n\r<br>", $validBidInfo));
		}
	}

	private function submitBidStep($html, array $bidInfo) {

		$bAmount = $bidInfo['bid_amount'];
		$financeType = $bidInfo['finance_type'];
		$sClosingCost = $bidInfo['seller_closing_cost'];
		$bCommissionCost = $bidInfo['broker_commission_cost'];
		$pType = $bidInfo['purchaser_type'];
		$acceptBackUpOffer = $bidInfo['accept_as_backup_offer'];
		//$pIdType = $bidInfo['purchaser_id_type'];
		$pIdNum = $bidInfo['purchaser_id_number'];
		$pCompanyName = $bidInfo['purchaser_company_name'];
		$pFirstName = $bidInfo['purchaser_first_name'];
		$pMiddleName = $bidInfo['purchaser_middle_name'];
		$pLastName = $bidInfo['purchaser_last_name'];
		$pAddress = $bidInfo['address'];
		$pCity = $bidInfo['city'];
		$pState = $bidInfo['state'];
		$pZip = $bidInfo['zip'];
		$pEmail = $bidInfo['email'];

		$enableSecondPurchaser = null;

		$hiddenInputData = array();
		foreach ($html->find('input[type=hidden]') as $hiddenInput) {
			$hiddenInputData[$hiddenInput -> name] = $hiddenInput -> value;
		}

		$agentInputData = array();
		foreach ($html->find("input[name^=txtSellingAgent]") as $agentInput) {
			$agentInputData[$agentInput -> name] = $agentInput -> value;
		}

		$listingBrokerComission = $bAmount * .03;
		$bCommissionCost = min(array(
			$listingBrokerComission,
			$bCommissionCost
		));
		$netBidAmount = $bAmount - ($listingBrokerComission + $sClosingCost + $bCommissionCost);

		$postData = array(
			'btnContinue' => 'Continue',

			'hdnBidAmount' => number_format($bAmount, 2),
			'txtBidAmount' => number_format($bAmount, 2),
			'txtClosingCosts' => number_format($sClosingCost, 2),
			'txtListingBrokerCommission' => number_format($listingBrokerComission, 2),
			'txtSellingBrokerCommission' => number_format($bCommissionCost, 2),
			'txtNetBidAmount' => number_format($netBidAmount, 2),
			'hdnDollarHome' => '',
			'rbBackupOffer' => $acceptBackUpOffer,
			'rbFinancingType' => $financeType,
			'rbOwnerType' => $pType,

			'rbPrimaryPurchaserType' => $pType,
			'txtPrimaryPurchaserAddress' => $pAddress,
			'txtPrimaryPurchaserCity' => $pCity,
			'ddPrimaryPurchaserState' => $pState,
			'txtPrimaryPurchaserZipCode' => $pZip,
			'txtPrimaryPurchaserCompanyName' => $pCompanyName,
			'txtPrimaryPurchaserEmail' => $pEmail,
			'txtPrimaryPurchaserFirstName' => $pFirstName,
			'txtPrimaryPurchaserMiddleName' => $pMiddleName,
			'txtPrimaryPurchaserLastName' => $pLastName,
			'txtPrimaryPurchaserSSNEIN' => $pIdNum,
			'txtPrimaryPurchaserSSNEINConfirm' => $pIdNum,
		);

		if (isset($bidInfo['purchaser_id_type2'])) {
			$enableSecondPurchaser = 'on';
			//$pIdType2 = $bidInfo['purchaser_id_type2'];
			$pIdNum2 = $bidInfo['purchaser_id_number2'];
			$pCompanyName2 = $bidInfo['purchaser_company_name2'];
			$pFirstName2 = $bidInfo['purchaser_first_name2'];
			$pMiddleName2 = $bidInfo['purchaser_middle_name2'];
			$pLastName2 = $bidInfo['purchaser_last_name2'];
			$pAddress2 = $bidInfo['address2'];
			$pCity2 = $bidInfo['city2'];
			$pState2 = $bidInfo['state2'];
			$pZip2 = $bidInfo['zip2'];
			$pEmail2 = $bidInfo['email2'];

			$postData['chkEnableSecondaryPurchaser'] = $enableSecondPurchaser;
			$postData['rbSecondaryPurchaserType'] = $pType;
			$postData['txtSecondaryPurchaserAddress'] = $pAddress2;
			$postData['txtSecondaryPurchaserCity'] = $pCity2;
			$postData['ddSecondaryPurchaserState'] = $pState2;
			$postData['txtSecondaryPurchaserZipCode'] = $pZip2;
			$postData['txtSecondaryPurchaserCompanyName'] = $pCompanyName2;
			$postData['txtSecondaryPurchaserEmail'] = $pEmail2;
			$postData['txtSecondaryPurchaserFirstName'] = $pFirstName2;
			$postData['txtSecondaryPurchaserMiddleName'] = $pMiddleName2;
			$postData['txtSecondaryPurchaserLastName'] = $pLastName2;
			$postData['txtSecondaryPurchaserSSNEIN'] = $pIdNum2;
			$postData['txtSecondaryPurchaserSSNEINConfirm'] = $pIdNum2;

		}

		// Include the hidden input data
		foreach ($hiddenInputData as $index => $value) {
			if (!isset($postData[$index])) {
				$postData[$index] = $value;
			}
		}

		// Include the agent data
		foreach ($agentInputData as $index => $value) {
			if (!isset($postData[$index])) {
				$postData[$index] = $value;
			}
		}

		//echo('Post Data (Step '.$this->capturedHtmlStep.'):<br>');
		//var_dump($postData);
		//foreach ($postData as $index=>$value){
		//echo($index.' = '.$value.'<br>');
		//}
		//echo('<br><br>');

		$postDataAsString = http_build_query($postData);

		$additionalCurlOptions = array(
			CURLOPT_POST => 1,
			CURLOPT_POSTFIELDS => $postDataAsString,
		);

		$bidSumbmitUrl = 'https://www.hudhomestore.com/pages/BidSubmission.aspx?Page=BidSubmission&PageGroup=Listing&sLanguage=ENGLISH&iHeight=0';

		$hudhomestoreBidConfirmation = $this -> get_web_page($bidSumbmitUrl, false, $additionalCurlOptions);

		$html = str_get_html($hudhomestoreBidConfirmation . ' ');

		if ($html === false) {
			echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($bidSumbmitUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
			return false;
		}
		else
		if ($this -> checkSessionExpired($html)) {
			echo("<b><font color='red'>Your Session has expired (After Submit Step " . $this -> capturedHtmlStep . "). Could not place bid</font></b><br>");
			$this -> logCapturedHtml($html, $bidInfo['bidId']);
			return false;
		}
		$this -> logCapturedHtml($html, $bidInfo['bidId']);

		// Then redirect to Bid Summary Page
		//$bidSummaryUrl = 'https://www.hudhomestore.com/Listing/BidSummary.aspx?sLanguage=ENGLISH';
		$bidSummaryUrl = 'https://www.hudhomestore.com/pages/BidSummary.aspx?Page=BidSummary&PageGroup=Listing&sLanguage=ENGLISH&iHeight=0';
		$bidHtml = $this -> get_web_page($bidSummaryUrl, false, array(CURLOPT_POST => false, ));

		$html = str_get_html($bidHtml . ' ');

		if ($html === false) {
			echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($bidSummaryUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
			return false;
		}
		else
		if ($this -> checkSessionExpired($html)) {
			echo("<b><font color='red'>Your Session has expired (After Submit Step " . $this -> capturedHtmlStep . "). Could not place bid</font></b><br>");
			$this -> logCapturedHtml($html, $bidInfo['bidId']);
			return false;
		}
		$this -> logCapturedHtml($html, $bidInfo['bidId']);

		//die("<br><br><hr><br><br>".$html);

		// Post acknowledgment to bid summary page. confirms your bid

		$postData2 = array(
			'chkAgreeToTermsAndConditions' => 1,
			'btnConfirm' => 'Confirm This Bid',
		);

		$hiddenInputData = array();
		foreach ($html->find('input[type=hidden]') as $hiddenInput) {
			$hiddenInputData[$hiddenInput -> name] = $hiddenInput -> value;
		}

		// Include the hidden input data
		foreach ($hiddenInputData as $index => $value) {
			if (!isset($postData2[$index])) {
				$postData2[$index] = $value;
			}
		}

		//echo('Post Data (Step '.$this->capturedHtmlStep.'):<br>');
		//var_dump($postData2);
		//foreach ($postData2 as $index=>$value){
		//echo($index.' = '.$value.'<br>');
		//}
		//echo('<br><br>');

		$postDataAsString2 = http_build_query($postData2);
		$additionalCurlOptions2 = array(
			CURLOPT_POST => 1,
			CURLOPT_POSTFIELDS => $postDataAsString2,
		);

		$bidSummaryAcknowledgeHtml = $this -> get_web_page($bidSummaryUrl, false, $additionalCurlOptions2);

		$html = str_get_html($bidSummaryAcknowledgeHtml . ' ');

		if ($html === false) {
			echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($bidSummaryUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
			return false;
		}
		else
		if ($this -> checkSessionExpired($html)) {
			echo("<b><font color='red'>Your Session has expired (After Submit Step " . $this -> capturedHtmlStep . "). Could not place bid</font></b><br>");
			$this -> logCapturedHtml($html, $bidInfo['bidId']);
			return false;
		}
		$this -> logCapturedHtml($html, $bidInfo['bidId']);

		//Go to the bid acknowledgment page to get confirmation number

		//$bidAcknowledgeUrl = 'https://www.hudhomestore.com/Listing/BidAcknowledgement.aspx?sLanguage=ENGLISH';
		$bidAcknowledgeUrl = 'https://www.hudhomestore.com/pages/BidAcknowledgement.aspx?Page=BidAcknowledgement&PageGroup=Listing&sLanguage=ENGLISH&iHeight=0';

		//$bidAcknowledgeHtml = $this -> get_web_page($bidAcknowledgeUrl,false,$additionalCurlOptions2);
		$bidAcknowledgeHtml = $this -> get_web_page($bidAcknowledgeUrl, false, array(CURLOPT_POST => false, ));

		$html = str_get_html($bidAcknowledgeHtml . ' ');

		if ($html === false) {
			echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($bidAcknowledgeUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
			return false;
		}
		else
		if ($this -> checkSessionExpired($html)) {
			echo("<b><font color='red'>Your Session has expired (After Submit Step " . $this -> capturedHtmlStep . "). Could not place bid</font></b><br>");
			$this -> logCapturedHtml($html, $bidInfo['bidId']);
			return false;
		}
		$this -> logCapturedHtml($html, $bidInfo['bidId']);

		// Get the confirmation number
		//lblHeaderBidReceiptConfirmationNumber
		$confirmationNumber = $html -> find('span[id=lblHeaderBidReceiptConfirmationNumber]', 0) -> plaintext;
		return $this -> updateBidWithConfirmationNumber($bidInfo['bidId'], $confirmationNumber);
	}

	private function updateBidWithConfirmationNumber($bidID, $confirmationNumber) {
		if (isset($confirmationNumber) && strlen($confirmationNumber) > 0) {
			$query = 'UPDATE user_bids set confirmation_number=\'' . trim($confirmationNumber) . '\', submission_time=NOW(), bid_status="Sealed Bid" WHERE id=' . $bidID;
			$this -> runQuery($query, $this -> getDBConnection() -> getDBConnection());
			return true;
		}
		return false;

	}

	private function updateBidWithBidStatus($bidID, $bidStatus) {
		if (isset($bidStatus) && strlen($bidStatus) > 0) {
			$query = 'UPDATE user_bids set bid_status=\'' . trim($bidStatus) . '\' WHERE id=' . $bidID;
			$this -> runQuery($query, $this -> getDBConnection() -> getDBConnection());
			return true;
		}
		return false;

	}

	private function updateBidWithBidCounterOfferAmount($bidID, $counterOfferAmount) {
		if (isset($counterOfferAmount) && strlen($counterOfferAmount) > 0) {
			$query = 'UPDATE user_bids set counter_offer_amount=\'' . (float)$this -> toPlainNumber($counterOfferAmount) . '\', has_counter_offer=true WHERE id=' . $bidID;
			$this -> runQuery($query, $this -> getDBConnection() -> getDBConnection());
			return true;
		}
		return false;

	}

	function toPlainNumber($str) {
		return preg_replace("/([^0-9\\.])/i", "", $str);
	}

	private function validBidInfo(array $bidInfo) {
		$mustBeSet = array(
			'user',
			'pass',
			'case',
			'NAID',
			'license',
			'bid_amount',
			'finance_type',
			'seller_closing_cost',
			'broker_commission_cost',
			'purchaser_type',
			'accept_as_backup_offer',
			//'purchaser_id_type',
			'purchaser_id_number',
			'purchaser_first_name',
			'purchaser_last_name',
			'address',
			'city',
			'state',
			'zip',
		);
		$mustBeANumber = array(
			'bid_amount',
			'seller_closing_cost',
			'broker_commission_cost',
			'zip',
			'zip2',
		);
		$errors = array();

		foreach ($mustBeSet as $index) {
			if (!isset($bidInfo[$index]) || strlen($bidInfo[$index]) == 0) {
				$errors[] = $index . ' Must be set.';
			}
		}

		foreach ($mustBeANumber as $index) {
			if (isset($bidInfo[$index]) && is_nan($bidInfo[$index])) {
				$errors[] = $index . ' Must be a number.';
			}
		}
		return (count($errors) == 0) ? true : $errors;

	}

	function agentLogintoHomeStores($user, $pass, $attempts = 1) {

		if (!isset($user) || strlen($user) == 0 || !isset($pass) || strlen($pass) == 0) {
			return false;
		}

		// Go to the home page to get the proper cookies set
		$homePageUrl = 'https://www.hudhomestore.com/Home/Index.aspx?sLanguage=ENGLISH';
		$homePageHtml = $this -> get_web_page($homePageUrl);
		$html = str_get_html($homePageHtml . ' ');
		$this -> logCapturedHtml($html, null, 'agent_login');

		$homePageHtml = $this -> get_web_page($homePageUrl);
		$html = str_get_html($homePageHtml . ' ');
		$this -> logCapturedHtml($html, null, 'agent_login');

		$html = str_get_html($homePageHtml . ' ');

		//echo('HTML after home page <br>'.$html.'<br><br><hr><br><br>');

		if ($html === false) {
			echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($homePageUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
			return false;
		}
		else
		if ($this -> checkSessionExpired($html)) {
			echo("<b><font color='red'>Your Session has expired (After Login Step " . $this -> capturedHtmlStep . "). Could not place bid</font></b><br>");
			$this -> logCapturedHtml($html, null, 'agent_login');
			return false;
		}
		$this -> logCapturedHtml($html, null, 'agent_login');

		// Go to the login page
		$loginUrl = 'https://www.hudhomestore.com/pages/CommonLogin.aspx?Page=Login&PageGroup=Listing&sLanguage=ENGLISH&iHeight=415';
		$logInHtml = $this -> get_web_page($loginUrl);

		$html = str_get_html($logInHtml . ' ');

		//echo('HTML after login page <br>'.$html.'<br><br><hr><br><br>');

		if ($html === false) {
			echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($loginUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
			return false;
		}
		else
		if ($this -> checkSessionExpired($html)) {
			echo("<b><font color='red'>Your Session has expired (After Login Step " . $this -> capturedHtmlStep . "). Could not place bid</font></b><br>");
			$this -> logCapturedHtml($html, null, 'agent_login');
			return false;
		}
		$this -> logCapturedHtml($html, null, 'agent_login');

		// Post the login data to the login page
		$postData = array(
			'btnLogin1' => 'Login',
			'sPassword1' => $pass,
			'sUsername1' => $user,
			'IsPageDirty' => 'false',
		);

		foreach ($html->find('input[type=hidden]') as $hiddenInput) {
			if (!isset($postData[$hiddenInput -> name])) {
				$postData[$hiddenInput -> name] = $hiddenInput -> value;
			}
		}

		//echo('Post Data:<br>');
		//var_dump($postData);
		//echo('<br>');

		$postDataAsString = http_build_query($postData);

		$additionalCurlOptions = array(
			CURLOPT_POST => 1,
			CURLOPT_POSTFIELDS => $postDataAsString,
		);

		$logInHtml = $this -> get_web_page($loginUrl, false, $additionalCurlOptions);

		$html = str_get_html($logInHtml . ' ');

		//echo('HTML after Loging in <br>'.$html.'<br><br><hr><br><br>');

		if ($html === false) {
			echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($loginUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
			return false;
		}
		else
		if ($this -> checkSessionExpired($html)) {
			echo("<b><font color='red'>Your Session has expired (After Login Step " . $this -> capturedHtmlStep . "). Could not place bid</font></b><br>");
			$this -> logCapturedHtml($html, null, 'agent_login');
			return false;
		}
		$this -> logCapturedHtml($html, null, 'agent_login');

		// Go to the individual user page to see if we are logged in
		$userLoggedInUrl = 'https://www.hudhomestore.com/pages/UserFilter.aspx?pageGroup=Bidder&sLanguage=ENGLISH&hideTranslationLink=';
		$userLoggedInHTML = $this -> get_web_page($userLoggedInUrl, false, array(CURLOPT_POST => false, ));

		$html = str_get_html($userLoggedInHTML . ' ');

		//echo('HTML after Loging in <br>'.$html.'<br><br><hr><br><br>');

		if ($html === false) {
			echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($userLoggedInUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
			return false;
		}
		else
		if ($this -> checkSessionExpired($html)) {
			echo("<b><font color='red'>Your Session has expired (After Login Step " . $this -> capturedHtmlStep . "). Could not place bid</font></b><br>");
			$this -> logCapturedHtml($html, null, 'agent_login');
			return false;
		}
		$this -> logCapturedHtml($html, null, 'agent_login');

		$loginWelcome = $html -> find('span[id=lblWelcome]', 0) -> plaintext;

		$loginSuccess = (isset($loginWelcome) && strlen($loginWelcome) > 0);

		if (!$loginSuccess) {
			if ($attempts > 0) {
				sleep(5);
				$loginSuccess = $this -> agentLogintoHomeStores($user, $pass, --$attempts);
			}
		}

		return $loginSuccess;

	}

}

$obj = new HHSPlaceBids();
?>